﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LibraryUtility.Data
{
    /// <summary>
    /// ClassName:ObjectCache
    /// Auther:Leo.wl
    /// Timw:2010-04-15
    /// </summary>
    public sealed class ObjectCache
    {
        /// <summary>
        /// Dictionary《K,T》 会自动维护一个空链表来保存不用的单元。
        /// 这里，使用被缓存对象的“弱引用”，允许这些对象被垃圾回收。
        /// </summary>
        private Dictionary<string, WeakReference> Buffer = new Dictionary<string, WeakReference>();
        /// <summary>
        /// Gets or sets the <see cref="System.Object"/> with the specified key.
        /// </summary>
        /// <value></value>
        public object this[string key]
        {
            get
            {
                WeakReference ret;
                if (Buffer.TryGetValue(key, out ret) && ret.IsAlive)
                    return ret.Target;
                else
                    return null;
            }
            set
            {
                WeakReference ret;
                if (Buffer.TryGetValue(key, out ret))
                    ret.Target = value;
                else
                    Buffer.Add(key, new WeakReference(value));
            }
        }
        /// <summary>
        /// Removes the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        public void Remove(string key)
        {
            Buffer.Remove(key);
        }
    }
}
